package com.freelancer.musicinstruction.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.freelancer.musicinstruction.R;
import com.freelancer.musicinstruction.activity.delegates.DialogManager;
import com.freelancer.musicinstruction.activity.delegates.ThreadManager;
import com.freelancer.musicinstruction.activity.delegates.YoutubeVideoAdapter;
import com.freelancer.musicinstruction.beans.interfaces.MusicInstruction;
import com.freelancer.musicinstruction.beans.youtube.YoutubeVideo;
import com.freelancer.musicinstruction.services.impl.youtube.YoutubeSearchService;
import com.freelancer.musicinstruction.services.interfaces.ISearchServices;

public class YoutubeList extends ListActivity {
		
	private static final String TAG = YoutubeList.class.getSimpleName();
		
	    private DialogManager dialogManager;
	    private ThreadManager threadManager;
	    private List<MusicInstruction> videos;
	    private YoutubeVideoAdapter video_adapter;
	    private EditText filterBox;
	    private TextView infoText;
	    ProgressBar progress;
	    Runnable downloadVideos;
	    StringBuilder sb;
	    YoutubeSearchService searchServices;
	   
	    
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	    	
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.youtube_list);
	        
	        progress = (ProgressBar) findViewById( android.R.id.empty );
	        infoText = (TextView) findViewById( R.id.infoview );
	        /*infoText.setFactory(this);

	        Animation in = AnimationUtils.loadAnimation(this,
	                android.R.anim.fade_in);
	        Animation out = AnimationUtils.loadAnimation(this,
	                android.R.anim.fade_out);
	        mSwitcher.setInAnimation(in);
	        mSwitcher.setOutAnimation(out);*/
	        
	        registerForContextMenu( getListView() );
	    	//getListView().setTextFilterEnabled( true );
	    	//getListView().setScrollbarFadingEnabled( true );
	    	
	        videos = new ArrayList<MusicInstruction>();
	        
	        video_adapter = new YoutubeVideoAdapter(this, R.layout.youtube_listitem, videos );
	        
	        setListAdapter( video_adapter );
	        
	        threadManager = ThreadManager.getInstance();
	        
	        dialogManager = new DialogManager( this );
	        
	        downloadVideos = new Runnable(){
				
				@Override
				public void run(){
					getVideos();
				}
			};
			
			threadManager.submitTask( downloadVideos );
			
			//filterBox = (EditText) findViewById(R.id.filter);
	        //filterBox.addTextChangedListener(filterTextWatcher);
	        //infoText.in
	        infoText.setText( "No Videos to Display ...");
	    }
	    
	    
	    private TextWatcher filterTextWatcher = new TextWatcher() {

	        public void afterTextChanged(Editable s) {
	        	
	        }

	        public void beforeTextChanged(CharSequence s, int start, int count,
	                        int after) {
	        }

	        public void onTextChanged(CharSequence s, int start, int before,
	                        int count) {
	        	video_adapter.getFilter().filter(s);
	        	progress.setVisibility( View.GONE );
	        	video_adapter.notifyDataSetChanged();
	        }

	};
	    
	    
	    @Override
	    public void onResume(){
	    	super.onResume();
	    	
	    }
	    
	    
	    @Override
	    public void onStart(){
	    	super.onStart();
	    	
	    }
	    
	    
	    @Override
	    protected void onDestroy() {
	    	super.onDestroy();
	        //filterBox.removeTextChangedListener(filterTextWatcher);
	    }
	    
	    
	    private void getVideos(){
	    	Log.d(TAG, "getVideos method called ");
			videos = new ArrayList<MusicInstruction>();
			
			
			try{
				Bundle bundle = getIntent().getExtras();
				sb = new StringBuilder();
				sb.append( bundle.getString("song_name") + " " );
				sb.append( bundle.getString("band_name") + " ");
				sb.append( bundle.getString("instrument") + " ");
				sb.append( "lesson");
				String query = URLEncoder.encode( sb.toString() );
				Log.d(TAG, "query string = "+query);
				
				String URL = "http://gdata.youtube.com/feeds/api/videos?" +
				"q="+ query + "&orderby=rating&alt=rss&format=6&" +
				"start-index=1&max-results=20&v=2&prettyprint=true";
	        	
	        	searchServices = new YoutubeSearchService( 20 );
	        	
	        	Log.d(TAG, "performing search over http");
	        	videos = (ArrayList<MusicInstruction>) searchServices.search( URL );
	        	
	        	if( videos != null ){
	        		Log.d(TAG, "Video Count: "+ videos.size() );
	        	}
	        	else{
	        		Log.d(TAG, "Did not receive any videos from query response" );
	        	}
	        	
	        	runOnUiThread( updateAdapter );
				
			}
			catch( Exception e ){
				Toast.makeText( this , "an error occurred: "+ e.getMessage(), Toast.LENGTH_SHORT).show();
				Log.e(TAG, e.getMessage() );
				progress.setVisibility( View.GONE );
			}
		}
		
		private Runnable updateAdapter = new Runnable(){

			@Override
			public void run() {
				Log.d(TAG, "updateAdapter runnable called ");
				if( videos != null && videos.size() > 0 ){
					video_adapter.notifyDataSetChanged();
					for( int i = 0; i < videos.size(); i++ ){
						video_adapter.add( videos.get( i ) );
						//Log.d(TAG, "video added to adapter");
					}
					
					progress.setVisibility( View.GONE );
					infoText.setText( "Displaying 1-"+ video_adapter.getCount() +" of "+ searchServices.getFeedHandler().getSearchResultsCount() + " videos for query \""+sb.toString()+"\"");
					video_adapter.notifyDataSetChanged();
					return;
				}
				
				infoText.setText( "Found 0 video matches for query\""+sb.toString()+"\"");
				progress.setVisibility( View.GONE );
				
			}
			
		};
		
		protected void onListItemClick(ListView l, View v, int position, long id ){
			
			YoutubeVideo video = (YoutubeVideo) videos.get( position );
			Log.d(TAG, "video title = "+video.getVideoTitle());
			
			Intent intent = new Intent( YoutubeList.this, YoutubeDetailsPage.class);
			
			intent.putExtra("video_title", video.getVideoTitle());
			intent.putExtra("video_id", video.getVideoID());
			intent.putExtra("video_url", video.getVideoLink());
			
			startActivity( intent );
			
			
		}
		
		
		
		
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {

			super.onCreateContextMenu(menu, v, menuInfo);
			menu.setHeaderTitle("Actions");
			menu.add(0, 0, 0, "Watch Video");
			menu.add(0, 1, 1, "Rate Video");
			menu.add(0, 2, 2, "Comment On Video");
			menu.add(0, 3, 3, "Share Video");
		}
		


		@Override
		public boolean onContextItemSelected(MenuItem item) {
			return super.onContextItemSelected(item);
		}

	}
